﻿using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace Ledict.ConditionExtract
{
    /// <summary>
    /// 表述库加工
    /// </summary>
    public partial class ExpressionProcess : Form
    {
        static ExpressionProcess _default;
        public static ExpressionProcess Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    _default = new ExpressionProcess();
                }
                return _default;
            }
        }


        public ExpressionProcess()
        {
            InitializeComponent();
        }
        TreeDataBLL trbll = new TreeDataBLL();
        Ledict.ConditionExtract.BLL.Express_WordBLL wordbll = new Express_WordBLL();
        ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        CaseCauseBLL casecausebLL = new CaseCauseBLL();
        AboutRegexBLL aboutreg = new AboutRegexBLL();
        ProcessDataSourceBLL datas = new ProcessDataSourceBLL();

        WorkThread_Public work = new WorkThread_Public();
        Express_MatchSituationBLL match = new Express_MatchSituationBLL();
        /// <summary>
        /// 各种排序
        /// </summary>
        enum Sort
        {
            WordLengSort,
            AlphabetSort,
            CountSort,
            RightSort,
            NotChooseSort
        }

        private string sort = "";
        private string IsASC = "";
        private string SelectText = "";
        private TreeNode clicknode = null;
        private string TypeName = "刑事案由";
        string EW_IDText = "";
        private string FirId = "1000";
        private List<TreeNode> NodeList = new List<TreeNode>();


        private void ExpressionStorage_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            CaseCauseTree();
        }

        #region 树

        public void CaseCauseTree()
        {
            #region 初始化
            this.tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            StacticQuery.Text = "";
            CurrNodeNum.Text = "";
            SumQuery.Text = "";
            #endregion

            DataTable dt = trbll.GetCauseTree_Two("",1);// 第一层
            if(dt.Rows .Count >0)
            {
                DataRow[] arrayDR = dt.Select("name='" + TypeName + "'");

                foreach (DataRow CaseTreeNodeRode in arrayDR)
                {
                    TreeNode node = new TreeNode();
                    node.Text = LdFormat.ObjectToString(CaseTreeNodeRode["name"]);
                    node.Tag = CaseTreeNodeRode["id"];
                    node.Name = LdFormat.ObjectToString(CaseTreeNodeRode["CC_NodeType"].ToString() + "," + CaseTreeNodeRode["TableName"].ToString());
                    FirId = CaseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 1).Rows.Count > 0)//第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }
           
        }
        /// <summary>
        /// 显示下一级树节点
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            DataTable CaseTreeNodeRode = GetChild(parentNode);
            if (CaseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < CaseTreeNodeRode.Rows.Count; i++)//下级
            {

                TreeNode node = new TreeNode();


                node.Text = LdFormat.ObjectToString(CaseTreeNodeRode.Rows[i]["name"]);
                node.Tag = CaseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(CaseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() + "," + CaseTreeNodeRode.Rows[i]["TableName"].ToString());

                if (GetChild(node).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }

                parentNode.Nodes.Add(node);
                NodeList.Add(node);
            }
        }
        //获取下一级树节点
        private DataTable GetChild(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            string pName = parentNode.Text.ToString();

            string[] name = parentNode.Name.ToString().Split(',');
            int ptype = Convert.ToInt32(name[0]);
            int TableName = Convert.ToInt32(name[1]);
            int childType = trbll.GetChildType(pid, ptype, TableName);//下级改去哪个表查0：CaseCause 1:SYS_Express_GroupSituation
            DataTable CaseTreeNodeRode;
            if (childType == 1)
            {

                if (TableName == 0) //如果是第一级 找组合单一
                {
                    int CC_IsCombination = 0;
                    SYS_CaseCause model = casecausebLL.GetCaseCauseByCCID(pid);
                    if (model != null && model.CC_IsCombination == 1)
                        CC_IsCombination = 1;
                    CaseTreeNodeRode = trbll.GetCauseTreeThree_ToExpressTab_Virtual(pid, CC_IsCombination);
                }
                else
                {
                    if (pName == "组合") //如果是组合的，去前缀
                        pid = pid.Substring(1, pid.Length - 1);
                    CaseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab(pid,1);//SYS_Express_GroupSituation 
                }
            }
            else
            {
                if (pName == "单一") //如果是组合的，去前缀
                    pid = pid.Substring(1, pid.Length - 1);
                CaseTreeNodeRode = trbll.GetCauseTree_Two(pid,1); //CaseCause
            }
            return CaseTreeNodeRode;

        }

        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node.FirstNode.Tag == null)
            {
                e.Node.Nodes.Clear();

                CaseCauseTreeChild(e.Node);
            }
        }
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (IsUseFul(e))
            {
                if (clicknode != null)
                {
                    clicknode.ForeColor = Color.Black;
                }
                clicknode = e.Node;

                clicknode.ForeColor = Color.Red;
            
                dataPagerMain.ChangePageNumber(1);
            }
        }
        #endregion

        /// <summary>
        /// 是否有用情形
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool IsUseFul(TreeViewEventArgs e)
        {

            //int type = Convert.ToInt32(e.Node.Name.ToString().Split(',')[0]);
            //if (type == 4 || type == 5 || type == 6 || type == 7 || type == 8)
            //{
                return true;
            //}

            //return false;
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
           
                if (clicknode != null)
                {
                    var startRowIndex = e.StartRowIndex;
                    var maximumRows = e.MaximumRows;
                    var endRowIndex = e.StartRowIndex + e.MaximumRows;
                    DataTable dt = new DataTable();
                    string id = clicknode.Tag.ToString();

                    //第一种表述节点
                    //第二种原SYS_CaseCause节点
                    int ismatch = IsMatch.Checked ? 1 : 0;
                    string AffirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                    id = expresitu.GetES_IDsByCCId(id, ismatch, AffirmIdeaResult);

                    dt = wordbll.GetExractContent(id, sort, IsASC, SelectText,"", 1);

                    if (dt.Rows.Count > 0)
                    {
                        e.TotalCount = dt.Rows.Count;
                        DataTable newdt = new DataTable();
                        newdt = dt.Clone();
                        DataRow[] dr = dt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                        for (int i = 0; i < dr.Length; i++)
                        {
                            newdt.ImportRow((DataRow)dr[i]);
                        }

                        dataGridView1.DataSource = newdt;
                    }
                    else
                    {
                        dataGridView1.DataSource = new DataTable();
                    }
                }
           
               
            
        }

        #region 各种排序
        private void WordLengSort_Click(object sender, EventArgs e)
        {
            sort = "WordLengSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void AlphabetSort_Click(object sender, EventArgs e)
        {
            sort = "AlphabetSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void CountSort_Click(object sender, EventArgs e)
        {
            sort = "CountSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        #endregion

        private void delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                    {
                        DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["DeleteRow"];
                        if (Convert.ToBoolean(check.Value) == true)
                        {
                            wordbll.Delete_Word(dataGridView1.Rows[i].Cells["EW_ID"].Value.ToString());
                           
                        }
                    }
                   
                  
               
                dataPagerMain.ChangePageNumber(1);

                if (dataGridView1.Rows.Count == 0)
                {
                    UpdateCC_IsShowExpress(clicknode);
                }
                MessageBox.Show("删除成功!");
                }
                catch (Exception error)
                {
                    MessageBox.Show("删除失败!");
                }
            }
        }

        /// <summary>
        /// 自己和所有父级节点记状态
        /// </summary>
        /// <param name="NowNode"></param>
        private void UpdateCC_IsShowExpress(TreeNode NowNode)
        {
            //查看节点关联的数据
            string Oldid = NowNode.Tag.ToString();
            string id = "";
            int count = 0;
            if (!Oldid.Contains("EMS"))
            {
                id = expresitu.GetES_IDsByCCId(Oldid, 1, "1");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText,"", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(Oldid, 1, "0");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText,"", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(Oldid, 0, "1");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText,"", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(Oldid, 0, "2");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText,"", 1).Rows.Count;
            }
            else
            {
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText,"", 1).Rows.Count;
            }
            //没数据且没下级
            if (NowNode.Nodes.Count == 0 && count == 0)
            {
                wordbll.UpdateCC_IsShowExpress(NowNode.Tag.ToString(), 0);
                TreeNode NowNodePID = NowNode.Parent;
                //去掉当前节点
                tVCaseCause.Nodes.Remove(NowNode);
              
                //递归处理父级 
                if (NowNodePID != null)
                    UpdateCC_IsShowExpress(NowNodePID);
            }
        }



        public void GetColor()
        {
            button8.BackColor = Color.White;
            button6.BackColor = Color.White;
            button5.BackColor = Color.White;
            button4.BackColor = Color.White;
            button7.BackColor = Color.White;
        }
        private void button8_Click(object sender, EventArgs e)
        {
            TypeName = "刑事案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }
        private void IsMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void NotMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void IsAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void NotAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
            }
        }

        private void UpdateWord_Click(object sender, EventArgs e)
        {
            if (wordbll.UpdateContent(EW_IDText, textBox1.Text))
            {
                MessageBox.Show("修改成功!");
            }
            else
            {
                MessageBox.Show("修改失败!");
            }
            dataPagerMain.ChangePageNumber(1);
        }

        #region 查询节点
        DataTable Querydt;
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                QueryNode();
            }

        }

        private void QueryNode()
        {
            string QueryNodeName =QueryNodeTxt.Text.Trim();

            if (QueryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, QueryNodeName, 2);
                StacticQuery.Text = Querydt.Rows.Count.ToString();
                if (Querydt.Rows.Count > 0)
                {
                    CurrNodeNum.Text = "1";
                    SumQuery.Text = CurrNodeNum.Text;
                    int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                    LinkIsVisible(CurrNode);
                    QueryNode_Page(Querydt, CurrNode);
                }
                else
                {
                    CurrNodeNum.Text = "0";
                    SumQuery.Text = CurrNodeNum.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }


        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            QueryNode();
        }
        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (CurrNodeNum.Text != "")
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) + 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }

        }
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (CurrNodeNum.Text != "")
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) - 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }

        }
        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                string[] NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');
                for (int i = 0; i < NotePidArr.Length; i++)
                {

                    if (i != NotePidArr.Length - 1)
                    {
                        FindNode(NotePidArr[i]).Expand();
                    }
                    else
                    {
                        TreeNode node = FindNode(NotePidArr[i]);
                        this.tVCaseCause.SelectedNode = node;

                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }
        /// <summary>
        /// 找到节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (TreeNode node in NodeList)
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;

        }

        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)
            {
                Prelinkbtn.Enabled = false;
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;
            }




        }
        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            int CurrNode = Convert.ToInt32(SumQuery.Text);

            if (Querydt.Rows.Count >= CurrNode)
            {
                CurrNodeNum.Text = SumQuery.Text;
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }

        #endregion 


      


       
       

      

      

       

    }

}